<template>
  <div class="doc-container">
    <div class="header">
      <el-button type="primary" @click="showUploadModal">导入文档</el-button>
      <el-button type="success" @click="reloadData">刷新状态</el-button>
      <span style="margin-left: 10px;color: #666;">温馨提示：请点击刷新状态，使表格的状态全部处于<span style="color: red;font-weight: 900;">已发布或待发布</span>，才点发布！！</span>
    </div>
    
    <el-table :data="docList" border style="width: 100%" class="doc-table">
      <el-table-column label="文档名称" width="250">
        <template #default="{ row }">
          {{ row.NewName?row.NewName:row.FileName }}
        </template>
      </el-table-column>
      <el-table-column prop="FileType" label="类型" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getFileTypeTag(row.FileType)">
            {{ row.FileType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="StatusDesc" label="状态" width="120" align="center">
        <template #default="{ row }">
          <span :class="['status', row.StatusDesc === '已发布' ? 'success' : 'error']">
            {{ row.StatusDesc }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="UpdateTime" label="更新时间" width="180" align="center">
        <template #default="{ row }">
          {{ formatTime(row.UpdateTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="DocCharSize" label="字符数量" width="200" align="center" />
      <el-table-column label="操作" width="250" align="center">
        <template #default="{ row }">
          <el-button size="small" @click="previewDoc(row)">预览</el-button>
          <el-button size="small" type="danger" @click="deleteDoc(row)">删除</el-button>
          <el-button size="small" @click="renameDoc(row)">重命名</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :total="pagination.total"
      @current-change="fetchDocs"
      class="pagination"
    />
    
    <DocUploadModal v-model="showUpload" @success="fetchDocs" />
  </div>
</template>

<script setup>
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import { ref, onMounted, computed } from 'vue'
import { useRoute } from "vue-router"
import { ListDoc,DeleteDoc,RenameDoc,GetDocPreview,createRelease,describeRelease } from "@/api/modules/auth"
import DocUploadModal from './DocUploadModal.vue'
import bus from '@/bus/index.js'
const route = useRoute()
const appId = computed(() => route.params.id)
const docList = ref([])
const showUpload = ref(false)
const pagination = ref({
  current: 1,
  size: 8,
  total: 0
})

// 获取文档列表
const fetchDocs = async () => {
  const res = await ListDoc(appId.value, 8, pagination.value.current)
  docList.value = res.data.List
  pagination.value.total = res.data.Total
}

// 时间戳转换
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp * 1000) // 假设是秒级时间戳
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 文件类型标签样式
const getFileTypeTag = (type) => {
  const map = {
    'pdf': 'danger',
    'doc': 'primary',
    'docx': 'primary',
    'xls': 'success',
    'xlsx': 'success',
    'ppt': 'warning',
    'pptx': 'warning'
  }
  return map[type.toLowerCase()] || ''
}

const showUploadModal = () => {
  showUpload.value = true
}

const previewDoc = async (row) => {
  // console.log('预览文档:', row)
  const res = await GetDocPreview(appId.value,row.DocBizId);
  // console.log(res,'res')
  if(res.status == 200){
    var url = 'https://lke.cloud.tencent.com/preview?id='+row.DocBizId+'&botBizId='+appId.value+'&test=1'
    window.open(url,'_blank')
  }
}

const deleteDoc = (row) => {
  try {
    ElMessageBox.confirm('确定删除该文档吗?', '提示', {
      type: 'warning'
    }).then(async res=>{
      const result = await DeleteDoc(row.DocBizId,appId.value);
      if(result.status == 200){
        ElMessage.success('删除成功')
        fetchDocs()
      }else{
        ElMessage.error('删除失败')
      }
    })
  } catch (e) {
    console.log('取消删除')
  }
}

const renameDoc = async (row) => {
  ElMessageBox.prompt('请输入新的文档名称', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async ({ value }) => {
    const result = await RenameDoc(appId.value,row.DocBizId,value+'.'+row.FileType);
    if(result.status == 200){
        ElMessage.success('重命名成功')
        fetchDocs()
      }else{
        ElMessage.error('重命名失败')
      }
  })
  .catch(() => {
    
  })
}

const reloadData = () =>{
  fetchDocs()
  ElMessage.success('刷新成功')
}
function areAllDocumentsPublished(docs) {
  return docs.every(doc => 
    doc.StatusDesc === "已发布" || doc.StatusDesc === "待发布"
  );
}
let setIntervalTimer = null;
onMounted(async () => {
  fetchDocs();
  bus.on("faBuZsMx",async ()=>{
    const loading = ElLoading.service({
      lock: true,
      text: "应用发布中...",
      background: "rgba(0, 0, 0, 0.7)",
    });
    // modifyApp()
    if(appId.value){
      // const res = await createRelease(appId.value);
      setIntervalTimer = setInterval(async ()=>{
        const res = await ListDoc(appId.value,1000,1);
        if(res.status == 200){

          const allPublished = areAllDocumentsPublished(res.data.List);
          if(allPublished){
            clearInterval(setIntervalTimer);
            const res = await createRelease(appId.value);
            console.log(res,'ewhjwfhke')
            if(res.status == 200){
              setIntervalTimer = setInterval(async ()=>{
                const res = await describeRelease(appId.value);
                if(res.data.Status == 3 || res.data.Status == 7 || res.data.Status == 9){
                  clearInterval(setIntervalTimer);
                  if(res.data.Status == 3){
                    ElMessage.success(res.data.StatusDesc);
                  }else{
                    ElMessage.error(res.data.StatusDesc);
                  }
                  loading.close();
                } 
              },3000)
            }else{
              loading.close();
              ElMessage.error('应用无需发布或发布错误！');
              clearInterval(setIntervalTimer);
            }
          }
        }
      },5000)
    }
  })
})
</script>

<style scoped>
.doc-container {
  /* padding: 20px; */
}

.header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.doc-table {
  margin-bottom: 20px;
}

.pagination {
  justify-content: flex-end;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status.success {
  color: #67c23a;
  background-color: #f0f9eb;
}

.status.error {
  color: #f56c6c;
  background-color: #fef0f0;
}
</style>